package com.uzai.console.web.vph;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.tb.tbtoken.TbTokenCallBackDto;
import com.uzai.console.dto.vph.vphtoken.VphTokenCallBackDto;
import com.uzai.console.entity.TbToken;
import com.uzai.console.entity.VphToken;
import com.uzai.console.service.vph.VphTokenService;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author jianghan
 * @date 2019-06-17 11:39
 */
@Api(value = "唯品会回调函数",tags = "唯品会|唯品会联盟", hidden = true)
@RestController
public class VphTokenCallbackController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(VphTokenCallbackController.class);

    @Autowired
    private VphTokenService vphTokenService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 回调获取授权
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "唯品会刷新授权回调函数", hidden = true)
    @ApiOperationSupport(order = 300)
    @GetMapping("/vph/callback")
    public void callback(String code,String state) throws Exception {
        logger.info("code:{},state:{}",new Object[]{code,state});

        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        param.add("grant_type","authorization_code");
        param.add("client_id", uzaiConsoleSysConfig.getVphTokenAppkey());
        param.add("client_secret", uzaiConsoleSysConfig.getVphTokenAppsecret());
        param.add("redirect_uri", uzaiConsoleSysConfig.getVphTokenCallback());
        param.add("request_client_ip", uzaiConsoleSysConfig.getVphTokenClientIp());
        param.add("code",code);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(uzaiConsoleSysConfig.getVphOauth2Token(), request, JSONObject.class);
        logger.info("vip access_token is :{}", Tools.getStrEmpty(JSONObject.toJSONString(response.getBody())));

        // 获取token 详情

        param = new LinkedMultiValueMap<>();
        param.add("access_token",response.getBody().getString("access_token"));

        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        request = new HttpEntity<>(param, headers);
        ResponseEntity<JSONObject> tokenInfoResp = restTemplate.postForEntity(uzaiConsoleSysConfig.getVphOauth2TokenInfo(), request, JSONObject.class);
        logger.info("vip access_token info is :{}",Tools.getStrEmpty(JSONObject.toJSONString(tokenInfoResp.getBody())));
        JSONObject tokenInfo = tokenInfoResp.getBody();
        String openId = tokenInfo.getString("open_id");
        String accessToken = tokenInfo.getString("access_token");
        String create_at = tokenInfo.getString("create_at");
        String expires_time = tokenInfo.getString("expires_time");

        int now = DateUtil.getNowTime();
        VphToken vipTokens = new VphToken();
        vipTokens.setId(IdWorker.getId());
        vipTokens.setOpenId(openId);
        vipTokens.setAccessToken(accessToken);
        vipTokens.setMerId(Long.parseLong(state));
        vipTokens.setAuthTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(create_at,"yyyy-MM-dd HH:mm:ss")));
        vipTokens.setExpiresTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(expires_time,"yyyy-MM-dd HH:mm:ss")));
        vipTokens.setCreateTime(now);
        vipTokens.setUpdateTime(now);
        try {
            vphTokenService.save(vipTokens);
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=1");
        } catch (Exception e) {
            logger.error("err:{}",e);
            String msg = "";
            if (e instanceof BusinessException){
                msg = e.getMessage();
            }
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=0&msg="+ URLEncoder.encode(msg,"UTF-8"));
        }
    }

    /**
     * 回调获取授权(2.0调用接口）
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "唯品会联盟刷新授权回调函数(2.0系统调用）")
    @PostMapping("/vph/oauth")
    public Object vphOauth(@RequestBody VphTokenCallBackDto vphTokenCallBackDto){
        vphTokenService.vphOauth(vphTokenCallBackDto);
        return true;
    }
}
